
#########################################################################

# Copyright (C) Flavio Piccinelli 2012 <flavio.picci@gmail.com>

#########################################################################

# ariaSrv.rb
# This file is part of "AriaAperta".

# AriaAperta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# AriaAperta is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AriaAperta.  If not, see <http://www.gnu.org/licenses/>.

#########################################################################
#########################################################################


#########################################################################
# Required libraries
#########################################################################
require "socket"
require "thread"
require "lib/MyThread"
require "lib/MySSL"
#########################################################################

include MySSL
include MyThread

def main()

	server = TCPServer.new(LIST_PORT)
	sslServer = MySSL::set_contxt(server)
	th_gr = ThreadGroup.new
	semaphore = Mutex.new
	Thread.abort_on_exception = true
	
	th = Thread.start do
		MyThread::thread_loop
	end
	th_gr.add(th)

	loop do
		begin
			th = Thread.start(sslServer.accept) do |sslSocket|
				puts "thread start"
				MyThread::thread_routine(sslSocket, semaphore)
			end
		rescue => error
			puts "error in thread: #{error}"
			retry
		end
		puts "adding thread"
		th_gr.add(th)
	end
	
ensure
	for th in th_gr.list
		th.join(5)
	end
end

puts "init"

main()

puts "exit"

exit 0
